package com.zl.csMall.product.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zl.csMall.basic.busFile.service.BusFileService;
import com.zl.csMall.mine.favorites.po.Favorites;
import com.zl.csMall.mine.favorites.service.FavoritesService;
import com.zl.csMall.mine.history.po.History;
import com.zl.csMall.mine.history.service.HistoryService;
import com.zl.csMall.product.commodity.mapper.CommodityMapper;
import com.zl.csMall.product.commodity.po.Commodity;
import com.zl.csMall.product.commodity.service.CommodityService;
import com.zl.csMall.product.commodity.vo.CountVisitorsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description: CommodityServiceImpl
 * @author: ChenNing
 * @date 2025-10-20 10:38
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements CommodityService {

    @Autowired
    private BusFileService busFileService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private FavoritesService favoritesService;


    @Override
    public boolean deleteById(long id) {
        LambdaQueryWrapper<Commodity> commodityQuery = new LambdaQueryWrapper<>();
        commodityQuery.select(Commodity::getId, Commodity::getMainAttachmentId, Commodity::getFrontAttachmentId,
                              Commodity::getAgainstAttachmentId, Commodity::getFeatureAttachmentId,
                              Commodity::getColorAttachmentId, Commodity::getInfoAttachmentId)
                .eq(Commodity::getId, id);
        Commodity commodity = this.getOne(commodityQuery, false);
        if (commodity == null || commodity.getId() == 0){
            return false;
        }
        boolean result = this.removeById(id);
        if (result){
            // 删除商品图片文件
            if (commodity.getMainAttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getMainAttachmentId());
            }
            if (commodity.getFrontAttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getFrontAttachmentId());
            }
            if (commodity.getAgainstAttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getAgainstAttachmentId());
            }
            if (commodity.getFeatureAttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getFeatureAttachmentId());
            }
            if (commodity.getColorAttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getColorAttachmentId());
            }
            if (commodity.getInfoAttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getInfoAttachmentId());
            }
            if (commodity.getExp1AttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getExp1AttachmentId());
            }
            if (commodity.getExp2AttachmentId() != null){
                busFileService.deleteByAttachmentId(commodity.getExp2AttachmentId());
            }
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> getSimpleList(LambdaQueryWrapper<Commodity> queryWrapper) {
        queryWrapper.select(Commodity::getId, Commodity::getNumber, Commodity::getName,
                Commodity::getFabricWidth, Commodity::getGramWeight, Commodity::getMainAttachmentId);
        List<Map<String, Object>> commodityList = this.listMaps(queryWrapper);
        int index = 0;
        for (Map<String, Object> commodityMap : commodityList){
            // 主图处理
            if (commodityMap.get("main_attachment_id") != null){
                long mainAttachmentId = Long.parseLong(commodityMap.get("main_attachment_id").toString());
                List<String> mainPicUrl = busFileService.getDowUrlByAttachmentId(mainAttachmentId);
                commodityMap.put("mainPicList", mainPicUrl);
            }
            commodityMap.put("mainAttachmentId", commodityMap.get("main_attachment_id"));
            commodityMap.remove("main_attachment_id");
            commodityList.set(index, commodityMap);
            index++;
        }
        return commodityList;
    }

    @Override
    public Page<Map<String, Object>> getSimplePage(LambdaQueryWrapper<Commodity> queryWrapper, Page page) {
        queryWrapper.select(Commodity::getId, Commodity::getNumber, Commodity::getName, Commodity::getIngredients,
                Commodity::getFabricWidth, Commodity::getGramWeight, Commodity::getMainAttachmentId);
        Page<Map<String, Object>> commodityPage = this.pageMaps(page, queryWrapper);
        List<Map<String, Object>> commodityList = commodityPage.getRecords();
        int index = 0;
        for (Map<String, Object> commodityMap : commodityList){
            // 主图处理
            if (commodityMap.get("main_attachment_id") != null){
                long mainAttachmentId = Long.parseLong(commodityMap.get("main_attachment_id").toString());
                List<String> mainPicUrl = busFileService.getDowUrlByAttachmentId(mainAttachmentId);
                commodityMap.put("mainPicList", mainPicUrl);
            }
            commodityMap.put("fabricWidth", commodityMap.get("fabric_width"));
            commodityMap.put("gramWeight", commodityMap.get("gram_weight"));
            commodityMap.put("mainAttachmentId", commodityMap.get("main_attachment_id"));
            commodityMap.remove("fabric_width");
            commodityMap.remove("gram_weight");
            commodityMap.remove("main_attachment_id");
            commodityList.set(index, commodityMap);
            index++;
        }
        return commodityPage.setRecords(commodityList);
    }

    @Override
    public Commodity getCommodity(long id) {
        Commodity commodity = this.getById(id);
        if (commodity == null || commodity.getId() == 0){
            return null;
        }
        // 主图处理
        if (commodity.getMainAttachmentId() != null){
            List<String> mainPicUrl = busFileService.getDowUrlByAttachmentId(commodity.getMainAttachmentId());
            commodity.setMainPicList(mainPicUrl);
        }
        // 正面图处理
        if (commodity.getFrontAttachmentId() != null){
            List<String> frontPicUrl = busFileService.getDowUrlByAttachmentId(commodity.getFrontAttachmentId());
            commodity.setFrontPicList(frontPicUrl);
        }
        // 反面图处理
        if (commodity.getAgainstAttachmentId() != null){
            List<String> againstPicUrl = busFileService.getDowUrlByAttachmentId(commodity.getAgainstAttachmentId());
            commodity.setAgainstPicList(againstPicUrl);
        }
        // 特写图处理
        if (commodity.getFeatureAttachmentId() != null){
            List<String> featurePicUrl = busFileService.getDowUrlByAttachmentId(commodity.getFeatureAttachmentId());
            commodity.setFeaturePicList(featurePicUrl);
        }
        // 颜色图处理
        if (commodity.getColorAttachmentId() != null){
            List<String> colorPicUrl = busFileService.getDowUrlByAttachmentId(commodity.getColorAttachmentId());
            commodity.setColorPicList(colorPicUrl);
        }
        // 详情图处理
        if (commodity.getInfoAttachmentId() != null){
            List<String> infoPicUrl = busFileService.getDowUrlByAttachmentId(commodity.getInfoAttachmentId());
            commodity.setInfoPicList(infoPicUrl);
        }
        // 扩展图1处理
        if (commodity.getExp1AttachmentId() != null){
            List<String> exp1PicUrl = busFileService.getDowUrlByAttachmentId(commodity.getExp1AttachmentId());
            commodity.setExp1PicList(exp1PicUrl);
        }
        // 扩展图2处理
        if (commodity.getExp2AttachmentId() != null){
            List<String> exp2PicUrl = busFileService.getDowUrlByAttachmentId(commodity.getExp2AttachmentId());
            commodity.setExp2PicList(exp2PicUrl);
        }
        return commodity;
    }

    @Override
    public Map<String, Object> getSimpleCommodity(long id) {
        LambdaQueryWrapper<Commodity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Commodity::getId, Commodity::getNumber, Commodity::getName, Commodity::getIngredients,
                Commodity::getFabricWidth, Commodity::getGramWeight, Commodity::getMainAttachmentId)
                .eq(Commodity::getId, id);
        Map<String, Object> commodityMap = this.getMap(queryWrapper);
        if (commodityMap == null || commodityMap.get("id") == null){
            return null;
        }
        // 主图处理
        if (commodityMap.get("main_attachment_id") != null){
            long mainAttachmentId = Long.parseLong(commodityMap.get("main_attachment_id").toString());
            List<String> mainPicUrl = busFileService.getDowUrlByAttachmentId(mainAttachmentId);
            commodityMap.put("mainPicList", mainPicUrl);
        }
        commodityMap.put("fabricWidth", commodityMap.get("fabric_width"));
        commodityMap.put("gramWeight", commodityMap.get("gram_weight"));
        commodityMap.put("mainAttachmentId", commodityMap.get("main_attachment_id"));
        commodityMap.remove("fabric_width");
        commodityMap.remove("gram_weight");
        commodityMap.remove("main_attachment_id");
        return commodityMap;
    }

    @Override
    public Page<Map<String, Object>> getHistoryByUserId(long userId, Page page) {
        // 该用户的历史浏览记录
        LambdaQueryWrapper<History> historyQuery = new LambdaQueryWrapper<>();
        historyQuery.select(History::getCommodityId)
                .eq(History::getUserId, userId)
                .orderByDesc(History::getCreateDate);
        page = historyService.page(page, historyQuery);
        List<History> historyList = page.getRecords();
        // 提取历史记录中的全部商品ID
        List<Long> commodityIdList = new ArrayList<>();
        for (History history : historyList){
            commodityIdList.add(history.getCommodityId());
        }
        // 查询历史记录商品信息
        if (commodityIdList.size() > 0){
            LambdaQueryWrapper<Commodity> commodityQuery = new LambdaQueryWrapper<>();
            commodityQuery.in(Commodity::getId, commodityIdList);
            List<Map<String, Object>> historyCommodityList = this.getSimpleList(commodityQuery);
            return page.setRecords(historyCommodityList);
        }
        return page;
    }

    @Override
    public Page<Map<String, Object>> getFavoritesByUserId(long userId, Page page) {
        // 该用户的收藏记录
        LambdaQueryWrapper<Favorites> favoritesQuery = new LambdaQueryWrapper<>();
        favoritesQuery.select(Favorites::getCommodityId)
                .eq(Favorites::getUserId, userId)
                .orderByDesc(Favorites::getCreateDate);
        page = favoritesService.page(page, favoritesQuery);
        List<Favorites> favoritesList = page.getRecords();
        // 提取收藏记录中的全部商品ID
        List<Long> commodityIdList = new ArrayList<>();
        for (Favorites favorites : favoritesList){
            commodityIdList.add(favorites.getCommodityId());
        }
        // 查询收藏记录商品信息
        if (commodityIdList.size() > 0){
            LambdaQueryWrapper<Commodity> commodityQuery = new LambdaQueryWrapper<>();
            commodityQuery.in(Commodity::getId, commodityIdList);
            List<Map<String, Object>> historyCommodityList = this.getSimpleList(commodityQuery);
            return page.setRecords(historyCommodityList);
        }
        return page;
    }

    @Override
    public Page<CountVisitorsVo> countVisitors(Page page) {
        // 浏览记录统计查询 - 按商品ID分组统计
        QueryWrapper<History> historyQuery = new QueryWrapper<>();
        historyQuery.select("commodity_id AS commodityId", "COUNT(*) AS counts")
                .groupBy("commodity_id")
                .orderByDesc("counts");
        page = historyService.pageMaps(page, historyQuery);
        List<Map<String, Object>> historyList = page.getRecords();

        List<CountVisitorsVo> dataList = new ArrayList<>();
        for (Map<String, Object> historyMap : historyList){
            // 商品处理
            long commodityId = Long.parseLong(historyMap.get("commodityId").toString());
            Map<String, Object> commodityMap = this.getSimpleCommodity(commodityId);

            CountVisitorsVo countVisitorsVo = new CountVisitorsVo();
            countVisitorsVo.setCount(Integer.parseInt(historyMap.get("counts").toString()));
            countVisitorsVo.setCommodityId(commodityId);
            countVisitorsVo.setCommodity(commodityMap);
            dataList.add(countVisitorsVo);
        }
        return page.setRecords(dataList);
    }

}
